package authz

default allow = false

#allow  {
#   trace(sprintf("%v : %v",["1" ,"2"]))
#   user_roles =  get_user_roles
#   user_white_list = get_user_white_list
#   trace(sprintf("%v : %v",[user_roles ,user_white_list]))
#   value := user_roles[index]
#   1==4
##   trace(sprintf("%v : %v",["1" ,"2"]))
#}


allow  {
   user_roles =  get_user_roles
   some index
   value := user_roles[index]
   not mach_labels(input.labels,value["labels"])
   match_method(input.method,value["method"])
}


#  ============ 检验method是否合适  ===========
match_method(input_method,role_methods){
    some index
    value := role_methods[index]
    value == "*"
}else{
  some index
     value := role_methods[index]
     value == input_method
}



#  ============ 校验labels是否合适  ===========
mach_labels(input_labels, role_labels){
  input_item_value:= input_labels[input_item_key]
  not  mach_label_all(input_item_key,input_item_value,role_labels)
}

# 匹配多个标签
mach_label_all(input_labe_key,input_labe_value,data_labels){
  data_item:= data_labels[data_item_key]
  mach_label_one(input_labe_value,data_item)
  mach_label_one(input_labe_key,data_item_key)
}

# 匹配一个标签
mach_label_one(inputdata,data2){
   data2 == "*"
}else {
   inputdata == data2
}




# ============ 校验白名单是否通过  ===========
match_white_list(clusterid,white_list){
   some i
   value := white_list[i]
   value == clusterid
}



# ======== 提供数据 ===========  数据生产者========
# 获取用户的角色
get_user_roles[user_roles] {
   some index
     role := data.data.user_roles.body.data[index]
       value := role[key]
       value == input.user
       # role["roles"] 类型为   ["view"] 开始遍历开始找到这个角色所有的权限
       some role_index
       role_name := role["roles"][role_index]
               # 将name相等的对象添加到数组
               some role_grants_index
               role_grant_item :=  data.data.role_grants.body.data[role_grants_index]
                   role_grant_item["name"] == role_name
                   user_roles:= role_grant_item

}


# 获取用户的白名单
get_user_white_list[user_white_list] {
   some index
     role := data.data.user_roles[index]
       value := role[key]
       value == input.user
       user_white_list := role["white_list"]
}





